package com.century.sjt.fragment;

import android.app.Activity;
import android.app.Fragment;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.century.sjt.R;
import com.century.sjt.activity.wallet.AddBankActivity;
import com.century.sjt.activity.wallet.BankCardActivity;
import com.century.sjt.activity.order.MyOrderDetailsActivity;
import com.century.sjt.activity.Pay.MerchantItemActivity;
import com.century.sjt.activity.wallet.WalletRechareActivity;
import com.century.sjt.activity.wallet.WalletToCosumeActivity;
import com.century.sjt.entity.BankCard;
import com.century.sjt.entity.Merchant;
import com.century.sjt.util.Constant;
import com.century.sjt.util.TimeButton;
import com.century.sjt.util.TipUtil;

import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * @author:周玲波
 * @Description: 绑定银行卡第二步
 * @date : 2016/8/22 14:17
 */
public class AddBankFragment_second extends Fragment {
    @BindView(R.id.et_bankcardtype)
     EditText etBankType;
    @BindView(R.id.et_phone)
    EditText etPhone;
    @BindView(R.id.et_identifying_code)
    EditText etCode;
    @BindView(R.id.btn_addnext_bank)
    Button btn_complete;
    @BindView(R.id.btn_get_sms_check)
     TimeButton btnGetVCode;
    @BindView(R.id.addback_cardtype)
    LinearLayout layoutCardType;
    private RequestQueue mQueue;
    String userName;
    String idCard;
    String bankCardNo;
    String phone;
    private String userId;
    String bankType;
    String vode;
    private String isRealName;
    SharedPreferences mainSharedPreferences;
    AddBankActivity bankActivity;
    private BankCard bankCard;
    private String sn;
    private String Type;
    private Merchant aMerchant;
    private String orderId = "";
    SendCodeFailClick mClick;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.sjt_bankcard_second_fragment, null);
        ButterKnife.bind(this,view);
        bankActivity= (AddBankActivity) getActivity();
        mQueue = Volley.newRequestQueue(bankActivity);
        initEvent(savedInstanceState);
        return view;
    }




    private void initEvent(Bundle savedInstanceState) {
        etBankType.setEnabled(false);
        etBankType.setText(bankType);
        Bundle bundle = getActivity().getIntent().getExtras();
        if(bundle!=null){
            phone = bundle.getString("phone");
            if ("6".equals(Type)){
                aMerchant=(Merchant)getActivity().getIntent().getSerializableExtra("Merchant");
            }
            if ("8".equals(Type)){
                orderId = getActivity().getIntent().getStringExtra("orderId");
            }
        }
        mainSharedPreferences = getActivity().getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
        userId = mainSharedPreferences.getString("userId", "");
        isRealName = mainSharedPreferences.getString("isRealName", "");
        if (bankCard.getStatus().equals("0")){
            layoutCardType.setVisibility(View.GONE);
            phone = bankCard.getPhone();
            btnGetVCode.OnStart();
            etPhone.setText(phone.substring(0,3) + " **** " + phone.substring(phone.length()-4,phone.length()));
        }
        btnGetVCode.onCreate(savedInstanceState);
        btnGetVCode.setTextAfter(getActivity().getResources().getString(R.string.btn_second)).setTextBefore(getActivity().getResources().getString(R.string.btn_get_verification_code)).setLenght(60 * 1000);//设置倒计时
        btnGetVCode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                    if (null==etPhone.getText().toString() || "".equals(etPhone.getText().toString())) {
                        TipUtil.showToast(getActivity().getResources().getString(R.string.error_no_phone), bankActivity, 1);
                    }else {
                        if (bankCard.getStatus().equals("0")){
                            resendAuthCode();
                        }else {
                            phone = etPhone.getText().toString().trim();
                            sendAuthCode();
                        }

                    }


            }

        });
        btn_complete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                vode = etCode.getText().toString().trim();
                if (etPhone.getText().toString() == null || etPhone.getText().toString().equals("")) {
                    TipUtil.showToast(getActivity().getResources().getString(R.string.error_no_phone), bankActivity, 1);
                }
//                else if (!Check.isMobileNO(etPhone.getText().toString())) {
//                    TipUtil.showToast(getResources().getString(R.string.error_phone),bankActivity, 1);
//                }
                else if (vode.equals("")) {
                    TipUtil.showToast(getActivity().getResources().getString(R.string.error_please_into_vcode), bankActivity, 1);
                }
                else {
                    if (bankCard.getStatus().equals("0")){
                        realNamePayActivate();
                    }else {
                        phone = etPhone.getText().toString().trim();
                        bindBankCard();
                    }

                }


            }
        });


    }

    //发送验证码
    private void sendAuthCode() {
        //显示Progress Dialog
        btnGetVCode.setTextAfter(getString(R.string.btn_second)).setTextBefore(getString(R.string.btn_get_verification_code)).setLenght(60*1000);//设置倒计时
        TipUtil.openProgressDialog(Constant.APPLICATION_NAME,getActivity(). getResources().getString(R.string.error_please_waitting),bankActivity);
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Constant.SendAuthCodeHost, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    TipUtil.closeProgressDialog();
                    JSONTokener jsonParser = new JSONTokener(response);
                    JSONObject res = (JSONObject) jsonParser.nextValue();
                    String code = res.getString("code");
                    String message = res.getString("message");
                    if (code.equals("200")) {
                        TipUtil.showToast(getString(R.string.error_sending_success), getActivity(), 1);
//                        JSONObject Data = res.getJSONObject("data");
//                        sn = Data.getString("sn");
                        btnGetVCode.setStart(true);
                        btnGetVCode.OnStart();

                    }else if (code.equals("500")){
                        getFragmentManager().popBackStack();
                        TipUtil.showToast(message, bankActivity, 1);
                    } else {
                        TipUtil.showToast(message, bankActivity, 1);
                    }
                } catch (JSONException ex) {
                    ex.printStackTrace();
                    TipUtil.showToast(getActivity().getResources().getString(R.string.error_service),bankActivity, 1);
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                TipUtil.showToast(getActivity().getResources().getString(R.string.error_network), bankActivity, 1);
                TipUtil.closeProgressDialog();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {

                Map<String, String> map = new HashMap<String, String>();
                map.put("loginId", userId);
                map.put("phone",etPhone.getText().toString().trim());
                //map.put("sn", sn);
                return map;

            }

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                SharedPreferences mainSharedPreferences = getActivity().getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String cookie = mainSharedPreferences.getString("cookie", "");
                String rememberMeValue = mainSharedPreferences.getString("rememberMe", "");
                HashMap localHashMap = new HashMap();
                String cookieValue = cookie + ";" + rememberMeValue;
                Log.e("cookie", cookieValue);
                localHashMap.put("Cookie", cookieValue);
                return localHashMap;
            }
        };
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(20000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        mQueue.add(stringRequest);

    }

    //重复发送验证码
    private void resendAuthCode() {
        //显示Progress Dialog
        btnGetVCode.setTextAfter(getActivity().getResources().getString(R.string.btn_second)).setTextBefore(getResources().getString(R.string.btn_get_verification_code)).setLenght(60 * 1000);//设置倒计时
        TipUtil.openProgressDialog(Constant.APPLICATION_NAME, getResources().getString(R.string.error_please_waitting),bankActivity);
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Constant.resendAuthCode, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    TipUtil.closeProgressDialog();
                    TipUtil.log("绑定银行卡发送验证码接口成功返回", response.toString(), 1);
                    JSONTokener jsonParser = new JSONTokener(response);
                    JSONObject res = (JSONObject) jsonParser.nextValue();
                    String code = res.getString("code");
                    String message = res.getString("message");
                    if (code.equals("200")) {//成功
                        TipUtil.showToast(getString(R.string.error_sending_success), getActivity(), 1);
                        btnGetVCode.setStart(true);
                        btnGetVCode.OnStart();
//                        etBankCardNo.setEnabled(false);
//                        etPhone.setEnabled(false);
                    } else {//失败
                        TipUtil.showToast(message, bankActivity, 1);
                    }
                } catch (JSONException ex) {
                    ex.printStackTrace();
                    TipUtil.showToast(getActivity().getResources().getString(R.string.error_service),bankActivity, 1);
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                TipUtil.showToast(getActivity().getResources().getString(R.string.error_network), bankActivity, 1);
                TipUtil.closeProgressDialog();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                map.put("loginId", userId);
                map.put("phone",phone);
                map.put("sn", sn);
                return map;

            }

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                SharedPreferences mainSharedPreferences = getActivity().getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String cookie = mainSharedPreferences.getString("cookie", "");
                String rememberMeValue = mainSharedPreferences.getString("rememberMe", "");
                HashMap localHashMap = new HashMap();
                String cookieValue = cookie + ";" + rememberMeValue;
                Log.e("cookie", cookieValue);
                localHashMap.put("Cookie", cookieValue);
                return localHashMap;
            }
        };
        mQueue.add(stringRequest);
    }


    private void bindBankCard() {
        //显示Progress Dialog
//        TipUtil.openProgressDialog(Constant.APPLICATION_NAME, getResources().getString(R.string.please_waitting), AddBankActivity.this);
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Constant.BindBankCardHost, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    TipUtil.closeProgressDialog();
                    TipUtil.log("绑定银行卡接口成功返回", response.toString(), 1);
                    JSONTokener jsonParser = new JSONTokener(response);
                    JSONObject res = (JSONObject) jsonParser.nextValue();
                    String code = res.getString("code");
                    String message = res.getString("message");
                    if (code.equals("200")) {//成功
                        if (isRealName.equals("0")) {
                            getRealNameInfo();
                        }

                        switch (Type) {
                            case "1"://充值
                                Intent intent1 = new Intent();
                                intent1.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                                intent1.putExtra("payType", "2");
                                intent1.setClass(getActivity(), WalletRechareActivity.class);
                                startActivity(intent1);
                                break;
                            case "2"://提现
                                Intent intent2 = new Intent();
                                intent2.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                                intent2.putExtra("payType", "2");
                                intent2.setClass(getActivity(), WalletToCosumeActivity.class);
                                startActivity(intent2);
                                break;
                            case "3"://银行
                                Intent intent3 = new Intent();
                                intent3.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                                intent3.putExtra("payType", "2");
                                intent3.setClass(getActivity(), BankCardActivity.class);
                                startActivity(intent3);
                                break;
                            case "4"://商家
                                Intent intent4 = new Intent();
                                intent4.setClass(getActivity(), MerchantItemActivity.class);
                                intent4.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                                Bundle mBundle = new Bundle();
                                mBundle.putSerializable("Merchant", aMerchant);
                                intent4.putExtras(mBundle);
                                intent4.putExtra("payType", "2");
                                startActivity(intent4);
                                break;
                            case "8"://订单
                                Intent intent21 = new Intent();
                                intent21.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                                intent21.putExtra("orderId", orderId);
                                intent21.putExtra("falg",3);
                                intent21.setClass(getActivity(), MyOrderDetailsActivity.class);
                                startActivity(intent21);
                                break;
                        }

                    } else {//失败
                        TipUtil.showToast(message, bankActivity, 1);
                    }
                } catch (JSONException ex) {
                    ex.printStackTrace();
                    TipUtil.showToast(getActivity().getResources().getString(R.string.error_service), bankActivity, 1);
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                TipUtil.showToast(getActivity().getResources().getString(R.string.error_network), bankActivity, 1);
                TipUtil.closeProgressDialog();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                map.put("loginId", userId);
                map.put("verificationCode", vode);
                map.put("sn", sn);
                return map;

            }

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                SharedPreferences mainSharedPreferences = getActivity().getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String cookie = mainSharedPreferences.getString("cookie", "");
                String rememberMeValue = mainSharedPreferences.getString("rememberMe", "");
                HashMap localHashMap = new HashMap();
                String cookieValue = cookie + ";" + rememberMeValue;
//                Log.e("cookie", cookieValue);
                localHashMap.put("Cookie", cookieValue);
                return localHashMap;
            }
        };
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(20000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

        mQueue.add(stringRequest);

    }

    /**
     * 查询实名信息
     */
    private void getRealNameInfo() {
        //显示Progress Dialog
        TipUtil.openProgressDialog(Constant.APPLICATION_NAME,getActivity(). getResources().getString(R.string.error_please_waitting), bankActivity);
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Constant.GetRealNameInfo, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    TipUtil.closeProgressDialog();
                    TipUtil.log("接口成功返回", response.toString(), 1);
                    JSONTokener jsonParser = new JSONTokener(response);
                    JSONObject res = (JSONObject) jsonParser.nextValue();
                    String code = res.getString("code");
                    String message = res.getString("message");
                    if (code.equals("200")) {//成功
//                        TipUtil.showToast("绑定成功", AddBankCheckActivity.this, 1);

                        SharedPreferences.Editor editor = mainSharedPreferences.edit();
                        editor.putString("idCard", idCard);
                        editor.putString("name", userName);
                        editor.putString("isRealName", "1");
                        editor.commit();

                    } else {//失败
                        TipUtil.showToast(message,bankActivity, 1);
                    }
                } catch (JSONException ex) {
                    ex.printStackTrace();
                    TipUtil.showToast(getActivity().getResources().getString(R.string.error_service), bankActivity, 1);
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                TipUtil.showToast(getActivity().getResources().getString(R.string.error_network), bankActivity, 1);
                TipUtil.closeProgressDialog();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                map.put("loginId", userId);
                return map;

            }

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                SharedPreferences mainSharedPreferences = getActivity().getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String cookie = mainSharedPreferences.getString("cookie", "");
                String rememberMeValue = mainSharedPreferences.getString("rememberMe", "");
                HashMap localHashMap = new HashMap();
                String cookieValue = cookie + ";" + rememberMeValue;
//                Log.e("cookie", cookieValue);
                localHashMap.put("Cookie", cookieValue);
                return localHashMap;
            }
        };
        mQueue.add(stringRequest);

    }
    /**
     * 快捷支付激活
     */
    private void realNamePayActivate() {
        //显示Progress Dialog
//        TipUtil.openProgressDialog(Constant.APPLICATION_NAME, getResources().getString(R.string.please_waitting), AddBankActivity.this);
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Constant.realNamePayActivate, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    TipUtil.closeProgressDialog();
                    TipUtil.log("接口成功返回", response.toString(), 1);
                    JSONTokener jsonParser = new JSONTokener(response);
                    JSONObject res = (JSONObject) jsonParser.nextValue();
                    String code = res.getString("code");
                    String message = res.getString("message");
                    if (code.equals("200")) {//成功
                        TipUtil.showToast(getActivity().getResources().getString(R.string.text_activation_success_quick_pay), getActivity(), 1);

                        Intent intent = new Intent();
                        intent.setClass(getActivity(), BankCardActivity.class);
                        startActivity(intent);
                        switch (Type){
                            case "5"://银行
                                Intent intent5 = new Intent();
                                intent5.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                                intent5.putExtra("payType", "5");
                                intent5.setClass(getActivity(), BankCardActivity.class);
                                startActivity(intent5);
                                break;
                            case "6"://商家
                                Intent intent6 = new Intent();
                                intent6.setClass(getActivity(), MerchantItemActivity.class);
                                intent6.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                                Bundle mBundle = new Bundle();
                                mBundle.putSerializable("Merchant", aMerchant);
                                intent6.putExtras(mBundle);
                                intent6.putExtra("payType", "2");
                                startActivity(intent6);
                                break;
                            case "7"://充值
                                Intent intent7 = new Intent();
                                intent7.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                                intent7.putExtra("payType", "7");
                                intent7.setClass(getActivity(), WalletRechareActivity.class);
                                startActivity(intent7);
                                break;
                            case "8"://订单
                                Intent intent21 = new Intent();
                                intent21.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                                intent21.putExtra("orderId", orderId);
                                intent21.putExtra("falg",3);
                                intent21.setClass(getActivity(), MyOrderDetailsActivity.class);
                                startActivity(intent21);
                                break;
                        }
                    } else {//失败
                        TipUtil.showToast(message, getActivity(), 1);
                    }
                } catch (JSONException ex) {
                    ex.printStackTrace();
                    TipUtil.showToast(getActivity().getResources().getString(R.string.error_service),getActivity(), 1);
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                TipUtil.showToast(getActivity().getResources().getString(R.string.error_network), getActivity(), 1);
                TipUtil.closeProgressDialog();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                map.put("loginId", userId);
                map.put("verificationCode", vode);
                map.put("sn",sn);
                return map;

            }

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                SharedPreferences mainSharedPreferences = getActivity().getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String cookie = mainSharedPreferences.getString("cookie", "");
                String rememberMeValue = mainSharedPreferences.getString("rememberMe", "");
                HashMap localHashMap = new HashMap();
                String cookieValue = cookie + ";" + rememberMeValue;
//                Log.e("cookie", cookieValue);
                localHashMap.put("Cookie", cookieValue);
                return localHashMap;
            }
        };
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(20000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

        mQueue.add(stringRequest);

    }

    public interface SendCodeFailClick{
        void onFailClick();
    }
    public void setSendCodeFailClick(SendCodeFailClick mClick){
             this.mClick=mClick;
    }
}
